import json
import shutil

import sys
sys.path.append('..')
import ansible.constants as C
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.module_utils.common.collections import ImmutableDict
from ansible.inventory.manager import InventoryManager
from ansible.parsing.dataloader import DataLoader
from ansible.playbook.play import Play
from ansible.plugins.callback import CallbackBase
from ansible.vars.manager import VariableManager
from ansible import context
from ansible.inventory.host import Host
from os import path
from utils.path_util import get_root_dir

def main():
    play_source = dict(
        name="Ansible Play",
        hosts=['192.168.50.219'],
        gather_facts='no',
        tasks=[
            #dict(action=dict(module='shell', args='ls'), register='shell_out'),
            dict(action=dict(module='win_copy', args=dict(src='/root/a.txt', dest='C:/'))),
            #dict(action=dict(module='command', args=dict(cmd='/usr/bin/uptime'))),
        ]
    )

    loader = DataLoader()
    #sources = [{"hostname": "192.168.50.219", "port": "5985", "username": "adminer", "password": "123456", "ansible_winrm_server_cert_validation":"ignore"}] #'192.168.50.219,'
    inventory = InventoryManager(loader=loader, sources=(path.join(get_root_dir(), 'playbook', 'hosts'),))

    variable_manager = VariableManager(loader=loader, inventory=inventory)

    my_host = '192.168.50.219'
    variable_manager.set_host_variable(host=my_host, varname="ansible_ssh_host", value='192.168.50.219')
    variable_manager.set_host_variable(host=my_host, varname="ansible_ssh_port", value='5985')
    variable_manager.set_host_variable(host=my_host, varname="ansible_ssh_user", value='adminer')
    variable_manager.set_host_variable(host=my_host, varname="ansible_ssh_pass", value='123456')
    variable_manager.set_host_variable(host=my_host, varname="ansible_connection", value='winrm')
    variable_manager.set_host_variable(host=my_host, varname="ansible_winrm_server_cert_validation", value='ignore')

    inventory.add_host(host='192.168.50.219', group='windows', port='5985')

    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    passwords = {} #dict(vault_pass='123456')
    #results_callback = ResultsCollectorJSONCallback()
    tqm = TaskQueueManager(
        inventory=inventory,
        variable_manager=variable_manager,
        loader=loader,
        passwords=passwords,
        #stdout_callback=results_callback,  # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
    )
    try:
        result = tqm.run(play)  # most interesting data for a play is actually sent to the callback's methods
    finally:
        # we always need to cleanup child procs and the structures we use to communicate with them
        tqm.cleanup()
        if loader:
            loader.cleanup_all_tmp_files()

    print(result)


if __name__ == "__main__":
    main()
